<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
interface lineType {
  from: number
  to: number
}

interface PropsType {
  lineList: lineType[]
  maxLength: number
}

const props = withDefaults(defineProps<PropsType>(), {
  lineList: () => [],
  maxLength: 0,
})

/* 定义canvas */
const myCanvas = ref()

onMounted(() => {
  init()
})

watch(
  () => props.lineList,
  () => {
    init()
  },
)

/* 划线 */
const init = () => {
  const h = 30
  props.lineList.map((el: lineType) => {
    drawLineWithArrow(0, (el.from - 1) * h, 100, (el.to - 1) * h, 8)
  })
}

const drawLineWithArrow = (
  startX: number,
  startY: number,
  endX: number,
  endY: number,
  arrowSize: number,
) => {
  const ctx = myCanvas.value.getContext('2d')
  ctx.beginPath()
  ctx.moveTo(startX, startY)
  ctx.lineTo(endX, endY)
  ctx.strokeStyle = 'black'
  ctx.lineWidth = 2
  ctx.stroke()

  // 保存当前状态
  ctx.save()

  // 计算箭头的方向向量
  const deltaX = endX - startX
  const deltaY = endY - startY
  // 标准化方向向量
  const norm = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  const normalizedX = deltaX / norm
  const normalizedY = deltaY / norm

  // 计算箭头起始点坐标
  const arrowX = endX - arrowSize * normalizedX
  const arrowY = endY - arrowSize * normalizedY

  // 绘制一个等腰三角形作为箭头
  ctx.beginPath()
  ctx.moveTo(endX, endY)
  ctx.lineTo(arrowX - (arrowSize / 2) * normalizedY, arrowY + (arrowSize / 2) * normalizedX)
  ctx.lineTo(arrowX + (arrowSize / 2) * normalizedY, arrowY - (arrowSize / 2) * normalizedX)
  ctx.fill()

  // 恢复之前的Canvas状态
  ctx.restore()
}
</script>
<template>
  <canvas ref="myCanvas" width="100" :height="maxLength * 30"></canvas>
</template>
<style lang="scss" scoped></style>
